package app.texas.com.devilfishhouse.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;


import com.universal_library.AppConfig;
import com.universal_library.activity.BaseBackActivity;
import com.universal_library.fragment.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

import app.texas.com.devilfishhouse.R;
import app.texas.com.devilfishhouse.myUtils.WLogger;

public class SimpleBackActivity extends BaseBackActivity {
    public final static String BUNDLE_KEY_PAGE = "bundle_key_page";
    public final static String BUNDLE_KEY_ARGS = "bundle_key_args";
    private static final String TAG = "simpleBackActivity";
    // 当一个对象仅仅被weak reference指向, 而没有任何其他strong reference指向的时候,
    // 如果GC运行, 那么这个对象就会被回收. weak reference的语法是:
    protected WeakReference<Fragment> mFragment;
    protected int mPageValue = -1;
    protected SimpleBackPage page;
    private int title = 0;
    private int icon = 0;
    private boolean showTitle;

    @Override
    public void startActivity(Intent intent) {
        View view = getCurrentFocus();
        if (view != null) {
            view.clearFocus();
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        super.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        initTitle();
        mTitleBar.setTitle(title);
        if (showTitle) {
            mTitleBar.setVisibility(View.VISIBLE);
        } else {
            mTitleBar.setVisibility(View.GONE);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mTitleBar.setTitle((Integer) msg.obj);
                    break;
                case 2:
                    break;
            }
        }
    };

    @Override
    protected void initBundle(Bundle bundle) {
        super.initBundle(bundle);
        Intent intent = getIntent();
        if (mPageValue == -1)
            mPageValue = intent.getIntExtra(BUNDLE_KEY_PAGE, 0);
        initFromIntent(mPageValue, getIntent());

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_simple_back;
    }

    private void initFromIntent(int mPageValue, Intent data) {
        if (data == null)
            throw new RuntimeException("必须提供一个可实现的界面的Fragment");
        page = SimpleBackPage.getPageByValue(mPageValue);
        if (page == null)
            throw new IllegalArgumentException("没有注册的页面" + mPageValue);
        title = page.getTitle();
        icon = page.getIcon();
        showTitle = page.isShowTitle();
        try {
            Fragment fragment = (Fragment) page.getClz().newInstance();
            Bundle budle = data.getBundleExtra(BUNDLE_KEY_ARGS);
            if (budle != null)
                fragment.setArguments(budle);
            FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
            trans.replace(R.id.fragment_container, fragment, TAG);
            trans.commitAllowingStateLoss();
            mFragment = new WeakReference<Fragment>(fragment);
        } catch (Exception e) {
            if (AppConfig.DEBUG)
                e.printStackTrace();
            throw new IllegalArgumentException("生成fragment错误，fragment值为：" + mPageValue);
        }
    }

    @Override
    public void onBackPressed() {
        try {
            if (mFragment != null && mFragment.get() != null && mFragment.get() instanceof BaseFragment) {
                BaseFragment bf = (BaseFragment) mFragment.get();
                if (!bf.onBackPressed()) {
                    super.onBackPressed();
                }

            } else {
                super.onBackPressed();
            }
        } catch (Exception e) {
            if (AppConfig.DEBUG)
                e.printStackTrace();
            WLogger.log("Exception" + e.getMessage());
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.ACTION_DOWN && mFragment.get() instanceof BaseFragment) {
            ((BaseFragment) mFragment.get()).onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }

    /////////////////////////////////////////////////
    @Override
    public void initData() {

    }


    @Override
    protected int getTitleRes() {
        return title;
    }

}
